package com.sharemarking.application.common.util;



import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.List;


@ServerEndpoint("/websocket/{userid}")

public class MWebSocket {

    @OnOpen
    public void onOpen(@PathParam("userid") String userid, Session session) {
        WebSocketUtils.put(userid, session);
    }

    @OnMessage(maxMessageSize=1024*1024*10)
    public void onMessage(String message,@PathParam("userid") String userid) throws IOException {
        WSBean bean = JSON.parseObject(message, WSBean.class);
        System.out.println("message:"+bean.getMessage().toString()+"from:"+bean.getFrom().toString()+"to:"+bean.getTo().toString());
            broadcast(bean.getMessage(), bean.getFrom(), bean.getTo(),bean.getType());
    }

    @OnError
    public void onError(@PathParam("userid") String userid, Throwable t) {
        WebSocketUtils.remove(userid);
    }

    @OnClose
    public void onClose(@PathParam("userid") String userid) {
        WebSocketUtils.remove(userid);
    }

    private void broadcast(String message, String from, String to,String type) throws IOException {
        if ("-1".equals(to)) {
            List<Session> sessions = WebSocketUtils.getOtherSession(from);
            
            //Employee e=WebSocketUtils.GetImg(from);
           // System.out.println(e.getName());
            if (sessions.size() > 0) {
                for (Session s : sessions) {
                    s.getAsyncRemote().sendText(from+","+type+","+message+",qun");
                    
                }
            }

        } else {
            Session session = WebSocketUtils.get(to);
            if (null != session && session.isOpen()) {
                session.getAsyncRemote().sendText(type+","+message+","+from+",person");
                
            } else {
                //获取自己的session
                Session self = WebSocketUtils.get(from);
                self.getAsyncRemote().sendText("已下线");
            }
        }

    }
}
